package com.zrq.myapplication.business;

import android.os.Handler;
import android.os.Looper;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络请求工具类
 */

public class HttpUntil {

    String mUrl;
    Map<String, String> mParam;
    HttpResponse mHttpResponse;

    Handler myHandler = new Handler(Looper.getMainLooper());

    private final OkHttpClient client = new OkHttpClient();


    /**
     * 成功和失败的回调接口
     */
    public interface HttpResponse{
        void onSuccess(Object object);

        void onFail(String error);
    }

    /**
     * 构造方法中传入回调接口
     */
    public HttpUntil(HttpResponse response) {
        this.mHttpResponse = response;
    }

    /**
     * 发送post请求
     */
    public void sendPostHttp(String url, Map<String, String> param) {

        sendHttp(url, param, true);
    }

    /**
     * 发送get请求
     */
    public void sendGetHttp(String url, Map<String, String> param) {

        sendHttp(url, param, false);
    }

    /**
     * post请求和get请求的最终调用，发送网络请求
     */
    private void sendHttp(String url, Map<String, String> param, boolean isPost) {

        mUrl = url;
        mParam = param;
        //http请求逻辑
        run(isPost);
    }

    /**
     * 网络请求的实现逻辑
     */
    private void run(boolean isPost) {
        //创建request请求
        final Request request = createRequest(isPost);
        //创建请求队列
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (mHttpResponse != null) {
                    myHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            /**
                             * 失败回调
                             */
                            mHttpResponse.onFail("请求错误");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                if (mHttpResponse == null) return;
                myHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!response.isSuccessful()) {
                            /**
                             * 失败回调
                             */
                            mHttpResponse.onFail("请求失败：code" + response);
                        } else {
                            try {
                                /**
                                 * 成功回调
                                 */
                                mHttpResponse.onSuccess(response.body().string());
                            } catch (IOException e) {
                                e.printStackTrace();
                                mHttpResponse.onFail("结果转换失败");

                            }
                        }
                    }
                });
            }
        });
    }


    /**
     * 创建request请求
     */
    private Request createRequest(boolean isPost) {
        Request request;
        if (isPost) {
            MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder();
            requestBodyBuilder.setType(MultipartBody.FORM);
            //遍历map请求参数

            Iterator<Map.Entry<String, String>> iterator = mParam.entrySet().iterator();
            while ((iterator.hasNext())) {
                Map.Entry<String, String> entry = iterator.next();
                requestBodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
            }
            //构建者模式新建网络请求
            request = new Request.Builder()
                    .url(mUrl)
                    .post(requestBodyBuilder.build()).build();

        } else {
            //URL拼接
            String urlStr = mUrl + "?" + MapParamToString(mParam);
            request = new Request.Builder().url(urlStr).build();
        }
        return request;
    }

    /**
     * URL拼接
     */
    private String MapParamToString(Map<String, String> param) {
        StringBuilder stringBuilder = new StringBuilder();
        Iterator<Map.Entry<String, String>> iterator = param.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            //key就是"tel"
            stringBuilder.append(entry.getKey() + "=" + entry.getValue() + "&");
        }
        //减 1 是为了去掉 “&” 符号，因为号码归属地查询只需前 7 位即可，所以此处减1可以省略，
        // 但为了后期功能扩展，还需加上
        String str = stringBuilder.toString().substring(0, stringBuilder.length()-1);
        return str;
    }

}
